#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
角色配置管理模块

提供角色配置、路径管理和数据加载功能。
"""

import json
import os
from pathlib import Path
from typing import Any, Dict, Optional

from core.utils.log import mylogger


class CharacterConfig:
    """角色配置管理类"""

    def __init__(self, character_name: str, model_name: Optional[str] = None):
        self.character_name = character_name
        self.model_name = model_name or "default"

        # 设置基础路径
        project_root = Path(__file__).parent.parent.parent
        self.base_dir = str(project_root / "data")

        self.character_dir = os.path.join(self.base_dir, "characters", character_name)
        self.memory_dir = os.path.join(self.base_dir, "memory")

        # 确保目录存在
        os.makedirs(self.character_dir, exist_ok=True)
        os.makedirs(os.path.join(self.memory_dir, "short_term"), exist_ok=True)
        os.makedirs(os.path.join(self.memory_dir, "long_term"), exist_ok=True)

    def get_character_config_path(self) -> str:
        """获取角色配置文件路径"""
        return os.path.join(self.character_dir, "character.json")

    def get_long_term_memory_path(self) -> str:
        """获取长期记忆文件路径"""
        return os.path.join(
            self.memory_dir, "long_term", f"{self.character_name}_{self.model_name}_long_memories.json"
        )

    def get_short_term_memory_path(self) -> str:
        """获取短期记忆文件路径"""
        return os.path.join(
            self.memory_dir, "short_term", f"{self.character_name}_{self.model_name}_short_memories.json"
        )

    def load_character_data(self) -> Dict[str, Any]:
        """加载角色配置数据"""
        config_path = self.get_character_config_path()

        if not os.path.exists(config_path):
            mylogger.warning(f"角色配置文件不存在: {config_path}")
            return {}

        try:
            with open(config_path, "r", encoding="utf-8") as f:
                return json.load(f)
        except Exception as e:
            mylogger.error(f"加载角色配置失败: {e}")
            return {}

    def load_long_term_memory(self) -> str:
        """加载长期记忆数据，只返回content内容"""
        memory_path = self.get_long_term_memory_path()

        if not os.path.exists(memory_path):
            mylogger.debug(f"长期记忆文件不存在: {memory_path}")
            return ""

        try:
            with open(memory_path, "r", encoding="utf-8") as f:
                memories = json.load(f)
                if isinstance(memories, list):
                    # 提取所有记忆的content字段
                    content_list = [memory.get('content', '') for memory in memories if isinstance(memory, dict)]
                    return "\n".join(content_list)
                return ""
        except Exception as e:
            mylogger.error(f"加载长期记忆失败: {e}")
            return ""

    def load_short_term_memory(self) -> str:
        """加载短期记忆数据，只返回content内容"""
        memory_path = self.get_short_term_memory_path()

        if not os.path.exists(memory_path):
            mylogger.debug(f"短期记忆文件不存在: {memory_path}")
            return ""

        try:
            with open(memory_path, "r", encoding="utf-8") as f:
                memories = json.load(f)
                if isinstance(memories, list):
                    # 提取所有记忆的content字段
                    content_list = [memory.get('content', '') for memory in memories if isinstance(memory, dict)]
                    return "\n".join(content_list)
                return ""
        except Exception as e:
            mylogger.error(f"加载短期记忆失败: {e}")
            return ""


class PromptManager:
    """提示词管理器，管理所有角色的配置实例"""

    def __init__(self):
        self.character_configs: Dict[str, CharacterConfig] = {}

    def get_character_config(
        self, character_name: str, model_name: Optional[str] = None
    ) -> CharacterConfig:
        """获取或创建角色配置实例"""
        config_key = f"{character_name}_{model_name or 'default'}"
        if config_key not in self.character_configs:
            self.character_configs[config_key] = CharacterConfig(character_name, model_name)
            mylogger.info(f"为 {character_name} (模型: {model_name or 'default'}) 创建了配置管理工具")

        return self.character_configs[config_key]

    def load_character_data(
        self, character_name: str, model_name: Optional[str] = None
    ) -> Dict[str, Any]:
        """加载指定角色的配置数据"""
        config = self.get_character_config(character_name, model_name)
        return config.load_character_data()

    def get_character_config_path(
        self, character_name: str, model_name: Optional[str] = None
    ) -> str:
        """获取指定角色的配置文件路径"""
        config = self.get_character_config(character_name, model_name)
        return config.get_character_config_path()


prompt_manager = PromptManager()
